/**
 * 通过使用公用的方法来get和set Storage，
 * 在方法中通过增加projectId前缀来区分不同的项目（增加projectId是为了防止在同一域中存在多个项目，导致Storage相互干扰）
 * 编写改方法时作者二狗未考虑到原型和继承
 */
export const useLocalStorage = {
  projectId: 'JCFX_' as const,
  setItem: (key: string, value: string) => {
    const customKey = useLocalStorage.projectId + key
    try {
      localStorage.setItem(customKey, value)
    } catch (error) {
      console.error(error)
    }
  },
  getItem: (key: string): string | null => {
    const customKey = useLocalStorage.projectId + key
    return localStorage.getItem(customKey)
  },
  removeItem: (key: string) => {
    const customKey = useLocalStorage.projectId + key
    localStorage.removeItem(customKey)
  },
  clear: () => {
    const keysToRemove = Object.keys(localStorage).filter(key => key.startsWith(useLocalStorage.projectId))
    keysToRemove.forEach(key => {
      try {
        localStorage.removeItem(key)
      } catch (error) {
        console.error(error)
      }
    })
  }
}
export const useSessionStorage = {
  projectId: 'JCFX_' as const,
  setItem: (key: string, value: string) => {
    const customKey = useSessionStorage.projectId + key
    try {
      sessionStorage.setItem(customKey, value)
    } catch (error) {
      console.error(error)
    }
  },
  getItem: (key: string): string | null => {
    const customKey = useSessionStorage.projectId + key
    return sessionStorage.getItem(customKey)
  },
  removeItem: (key: string) => {
    const customKey = useSessionStorage.projectId + key
    sessionStorage.removeItem(customKey)
  },
  clear: () => {
    const keysToRemove = Object.keys(sessionStorage).filter(key => key.startsWith(useSessionStorage.projectId))
    keysToRemove.forEach(key => {
      try {
        sessionStorage.removeItem(key)
      } catch (error) {
        console.error(error)
      }
    })
  }
}
